package com.jhuster.jnote;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

//import butterknife.ButterKnife;
//import butterknife.Bind;

public class SignupActivity extends AppCompatActivity {
    private static final String TAG = "SignupActivity";

    /*@Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_address) EditText _addressText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_mobile) EditText _mobileText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.input_reEnterPassword) EditText _reEnterPasswordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Bind(R.id.link_login) TextView _loginLink;*/

    private EditText _nameText;
    //private EditText _addressText;
    private EditText _emailText;
    //private EditText _mobileText;
    private EditText _passwordText;
    private EditText _reEnterPasswordText;

    private Button _signupButton;
    private TextView _loginLink;





    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        //ButterKnife.bind(this);



        _nameText=(EditText) findViewById(R.id.input_name);
        //_addressText=(EditText) findViewById(R.id.input_address);
        _emailText=(EditText) findViewById(R.id.input_email);
        //_mobileText=(EditText) findViewById(R.id.input_mobile);
        _passwordText=(EditText) findViewById(R.id.input_password);
        _reEnterPasswordText=(EditText) findViewById(R.id.input_reEnterPassword);

        _signupButton=(Button) findViewById(R.id.btn_signup);
        _loginLink=(TextView) findViewById(R.id.link_login);






        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    // 进行点击事件后的逻辑操作
                    signup();
                }

            }
        });

        _loginLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Finish the registration screen and return to the Login activity
                Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }
        });
    }

    public void signup() {
        Log.d(TAG, "Signup");

        if (!validate()) {
            onSignupFailed();
            return;
        }

        _signupButton.setEnabled(false);

        final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
                R.style.AppTheme_Dark_Dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Creating Account...");
        progressDialog.show();

        String name = _nameText.getText().toString();
        //String address = _addressText.getText().toString();
        String email = _emailText.getText().toString();
        //String mobile = _mobileText.getText().toString();
        String password = _passwordText.getText().toString();
        String reEnterPassword = _reEnterPasswordText.getText().toString();

        // TODO: Implement your own signup logic here.

        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        // On complete call either onSignupSuccess or onSignupFailed
                        // depending on success
                        onSignupSuccess();
                        // onSignupFailed();
                        progressDialog.dismiss();
                    }
                }, 2000);
    }


    public void onSignupSuccess() {
        _signupButton.setEnabled(true);

        Intent intent=new Intent();
        String email = _emailText.getText().toString();
        String password = _passwordText.getText().toString();//获取输入的邮箱和密码
        intent.putExtra("email",email);
        intent.putExtra("password",password);//将数据绑定到intent上

        setResult(RESULT_OK, intent);//回传result_ok为resultcode
        finish();
    }

    public void onSignupFailed() {
        Toast.makeText(getBaseContext(), "Signup failed", Toast.LENGTH_LONG).show();

        _signupButton.setEnabled(true);
    }



    private Thread newThread;         //声明一个子线程
    static Socket client;
    public static volatile boolean valid=true;

    public boolean validate() {
        valid = true;

        String name = _nameText.getText().toString();
        //String address = _addressText.getText().toString();
        String email = _emailText.getText().toString();
        //String mobile = _mobileText.getText().toString();
        String password = _passwordText.getText().toString();
        String reEnterPassword = _reEnterPasswordText.getText().toString();

        if (name.isEmpty() || name.length() < 3) {
            _nameText.setError("at least 3 characters");
            valid = false;
        } else {
            _nameText.setError(null);
        }

        /*if (address.isEmpty()) {
            _addressText.setError("Enter Valid Address");
            valid = false;
        } else {
            _addressText.setError(null);
        }*/

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            _emailText.setError("enter a valid email address");
            valid = false;
        } else {
            _emailText.setError(null);
        }

        /*if (mobile.isEmpty() || mobile.length()!=10) {
            _mobileText.setError("Enter Valid Mobile Number");
            valid = false;
        } else {
            _mobileText.setError(null);
        }*/

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            _passwordText.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            _passwordText.setError(null);
        }

        if (reEnterPassword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPassword.equals(password))) {
            _reEnterPasswordText.setError("Password Do not match");
            valid = false;
        } else {
            _reEnterPasswordText.setError(null);
        }


        if(name.isEmpty() || name.length() < 3||email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()||password.isEmpty() || password.length() < 4 || password.length() > 10||reEnterPassword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPassword.equals(password))){

        }else{
            newThread=new Thread() {
                @Override
                public void run() {
                    //这里写入子线程需要做的工作
                    String result="";
                    String name = _nameText.getText().toString();
                    String email=_emailText.getText().toString();
                    String password=_passwordText.getText().toString();
                    try {

                        //client = new Socket("e1868x8452.iok.la", 22329);
                        client = new Socket();
                        SocketAddress socketAddress = new InetSocketAddress("e1868x8452.iok.la", 22329);
                        client.connect(socketAddress,3000);//单位为毫秒




                        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
                        DataInputStream dis = new DataInputStream(client.getInputStream());
                        dos.writeUTF("regist");
                        dos.flush();
                        dos.writeUTF(name +" "+ email + " " + password);
                        dos.flush();
                        result = dis.readUTF();
                        if (dos != null)
                            dos.close();
                        if (result != null) {
                            switch (result) {
                                case "registsuccess":
                                    //formula.setText("login");
                                    //Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
                                    //startActivityForResult(intent, 0);
                                    //finish();
                                    //overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                                    _nameText.setError(null);
                                    _emailText.setError(null);
                                    _passwordText.setError(null);
                                    _reEnterPasswordText.setError(null);
                                    break;
                                case "emailhasbeenregisted":
                                    _emailText.setError("email has been registed");
                                    valid = false;
                                    break;
                                /*case "emailnotregist":
                                    _emailText.setError("email address is not regist");
                                    valid = false;
                                    break;*/
                                default:
                                    valid = false;
                                    break;
                            }
                        }else{

                            Toast.makeText(getBaseContext(), "Lost connection!", Toast.LENGTH_LONG).show();

                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                        valid=false;
                        //_emailText.setError("连接失败");
                        //Looper.prepare();
                        //Toast.makeText(getBaseContext(), "Lost connection!", Toast.LENGTH_LONG).show();
                        //Looper.loop();   //会卡死回不到主线程

                    }
                }
            };
            newThread.start();
            try {
                newThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }//如果子线程没执行完毕数据不会改变
        }




        return valid;
    }
}